package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.utils.BeanCopyUtils;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationReqVo;
import com.atguigu.gulimall.product.vo.AttrGroupWithAttrsVo;
import com.atguigu.gulimall.product.vo.SpuItemAttrGroupVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    AttrDao attrDao;

    @Autowired
    AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {

        String key = (String) params.get("key");
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>();
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(obj -> obj.like("attr_group_id", key)
                    .or()
                    .like("attr_group_name", key));
        }
        if (catelogId == 0) {
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    wrapper
            );
            return new PageUtils(page);
        } else {
            wrapper.eq("catelog_id", catelogId);
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    wrapper
            );
            return new PageUtils(page);
        }
    }

    /**
     * 获取属性分组的关联的所有属性
     *
     * @param attrgroupId 分组id
     * @return 属性列表
     */
    @Override
    public List<AttrEntity> queryAttrListByGroupId(Long attrgroupId) {

        // 获取属性&属性分组关联表中该分组的记录
        List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        // 如果该属性分组没有关联
        if (CollectionUtils.isEmpty(relationEntityList)) {
            return Collections.emptyList();
        }

        // 过滤出该分组下的属性id
        List<Long> attrIdList = relationEntityList.stream()
                .map(AttrAttrgroupRelationEntity::getAttrId)
                .distinct()
                .collect(Collectors.toList());

        return attrDao.selectBatchIds(attrIdList);

    }

    /**
     * 删除属性与分组的关联关系
     *
     * @param relationReqVos 属性&属性分组关联请求vo
     */
    @Override
    public void removeAttrRelation(List<AttrGroupRelationReqVo> relationReqVos) {
        List<AttrAttrgroupRelationEntity> relationEntityList = BeanCopyUtils.copyList(relationReqVos, AttrAttrgroupRelationEntity.class);
        attrAttrgroupRelationDao.deleteBatchRelation(relationEntityList);
    }

    /**
     * 获取属性分组里面还没有关联的本分类里面的其他基本属性
     *
     * @param params      分页参数
     * @param attrgroupId 属性分组id
     * @return 属性分组里面还没有关联的本分类里面的其他基本属性
     */
    @Override
    public PageUtils queryNoattrRelationByGroupId(Map<String, Object> params, Long attrgroupId) {
        AttrGroupEntity attrGroupEntity = baseMapper.selectById(attrgroupId);

        // 1.查询属性分组所属分类的所有分组id
        List<Long> attrIdList = new ArrayList<>();
        List<AttrGroupEntity> groupEntityList = baseMapper.selectList(
                new QueryWrapper<AttrGroupEntity>()
                        .eq("catelog_id", attrGroupEntity.getCatelogId()));
        if (!CollectionUtils.isEmpty(groupEntityList)) {
            List<Long> groupIdList = groupEntityList.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());

            // 2.查询属性分组所属分类的所有已关联的属性id
            List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(
                    new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .in("attr_group_id", groupIdList));
            attrIdList = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        }

        // 3.查询属性分组所属分类下的未被关联的全部基本属性
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>();
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(obj -> obj.like("attr_id", key)
                    .or()
                    .like("attr_name", key));
        }
        wrapper.eq("catelog_id", attrGroupEntity.getCatelogId())
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (!CollectionUtils.isEmpty(attrIdList)) {
            wrapper.notIn("attr_id", attrIdList);
        }

        IPage<AttrEntity> page = attrService.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 添加属性与分组关联关系
     *
     * @param relationReqVos 属性&属性分组关联请求vo
     */
    @Override
    public void saveAttrRelation(List<AttrGroupRelationReqVo> relationReqVos) {
        List<AttrAttrgroupRelationEntity> relationEntityList = BeanCopyUtils.copyList(relationReqVos, AttrAttrgroupRelationEntity.class);
        attrAttrgroupRelationService.saveBatch(relationEntityList);
    }

    /**
     * 获取分类下所有分组&关联属性
     *
     * @param catelogId 分类id
     * @return 分组&关联属性列表
     */
    @Override
    public List<AttrGroupWithAttrsVo> queryGroupAndRelationAttrByCatId(Long catelogId) {
        // 1.获取该分类下所有分组
        List<AttrGroupEntity> attrGroupEntityList = attrGroupDao.selectList(
                new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        if (CollectionUtils.isEmpty(attrGroupEntityList)) {
            return Collections.emptyList();
        }

        // 2.对每个分组进行封装
        List<AttrGroupWithAttrsVo> data = attrGroupEntityList.stream().map(attrGroupEntity -> {
            // 2.1封装分组基本信息
            AttrGroupWithAttrsVo respVo = BeanCopyUtils.copy(attrGroupEntity, AttrGroupWithAttrsVo.class);

            // 2.2封装分组关联属性
            List<AttrEntity> attrEntityList = attrGroupService.queryAttrListByGroupId(respVo.getAttrGroupId());
            if (CollectionUtils.isEmpty(attrEntityList)) {
                respVo.setAttrs(Collections.emptyList());
                return respVo;
            }
            List<AttrGroupWithAttrsVo.AttrInfo> attrInfoList = attrEntityList.stream().map(attrEntity -> {
                AttrGroupWithAttrsVo.AttrInfo attrInfo = BeanCopyUtils.copy(attrEntity, AttrGroupWithAttrsVo.AttrInfo.class);
                attrInfo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
                return attrInfo;
            }).collect(Collectors.toList());
            respVo.setAttrs(attrInfoList);
            return respVo;
        }).collect(Collectors.toList());

        return data;
    }

    /**
     * 根据spuid获取spu的规格参数信息
     *
     * @param spuId     spuid
     * @param catelogId 分类id
     * @return spu的规格参数信息
     */
    @Override
    public List<SpuItemAttrGroupVo> getAttrGroupWithAttrsBySpuId(Long spuId, Long catelogId) {
        // 查出当前spu对应的所有属性的分组信息以及当前分组下的所有属性对应的值
        return baseMapper.getAttrGroupWithAttrsBySpuId(spuId, catelogId);
    }

}